package com.heima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.apis.article.IArticleClient.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 审核图片和文本用的
     */
    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    /**
     * 从minio下载图片
     */
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 保存app端文章数据
     */
    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 敏感词
     */
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 图片ocr
     */
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     *
     * 自媒体文章审核
     *
     * @param id
     */
    @Async  //标明当前方法是一个异步方法
    @Override
    public void autoScanWmNews(Integer id) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        //2.从内容中提取纯文本内容和图片
        HashMap<String, Object> map = handleTextAndImages(wmNews);

        //自管理敏感词过滤
        boolean isSensitive = handleSensitiveScan((String) map.get("content"), wmNews);
        if(!isSensitive){
            return;
        }



 /*       //3.审核文本内容  阿里云接口
        boolean isTextScan = handleTextScan((String) map.get("content"),wmNews);
        if (!isTextScan){
            return;
        }

        //4.审核图片  阿里云接口

        boolean image = handleImageScan((List<String>) map.get("image"), wmNews);
        if (!image){
            return;
        }*/

        //5.审核成功，保存app端的相关的文章数据
        ResponseResult result = saveAppArticle(wmNews);
        if(!result.getCode().equals(200)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //TODO 这个回填为什么
        //回填article_id  自媒体文章表关联app端文章表
        wmNews.setArticleId((Long) result.getData());

        updateWmNews(wmNews,(short) 9,"审核成功");
    }



    /**
     * 保存app端的相关的文章数据
     * @param wmNews
     * @return
     */
    public ResponseResult saveAppArticle(WmNews wmNews) {
  /*      //测试服务降级
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
*/

        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getId());
        if (wmChannel != null){
            articleDto.setChannelName(wmChannel.getName());
        }
        articleDto.setCreatedTime(new Date());
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null){
            articleDto.setAuthorName(wmUser.getName());
        }

        if (wmNews.getArticleId() != null){
            articleDto.setId(wmNews.getArticleId());
        }
        ResponseResult result = iArticleClient.saveArticle(articleDto);
        return result;
    }

    /**
     *处理自媒体的文章和图片
     * @param wmNews
     */
    public HashMap<String, Object> handleTextAndImages(WmNews wmNews){

        String content = wmNews.getContent();
        List<Map> maps = JSON.parseArray(content,Map.class);


        List<String> imagesUrlList = new ArrayList<>();
        //TODO StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        for (Map map : maps) {
            //TODO 这里不是==，而是equals
            if (map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                imagesUrlList.add((String) map.get("value"));
            }
        }

        //将封面图片放入imagesUrlList ，封面图片是个集合
        //判断封面图片集合不为空
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            //转为集合
            List<String> list = Arrays.asList(split);
            //TODO addAll
            imagesUrlList.addAll(list);
        }

        //将图片集合和文本集合都放到map中保存
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content",stringBuilder.toString());
        hashMap.put("image",imagesUrlList);

        return hashMap;
    }

    /**
     * 审核文本
     * @param content
     * @param wmNews
     * @return
     */
    public boolean handleTextScan(String content,WmNews wmNews){
        boolean flag= true;
        //参数校验
        if ((wmNews.getTitle()+","+content).length() == 0){
            return flag;
        }

        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map.get("suggestion").equals("block")){
                flag = false;
                //更新文章状态  2
                updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容");
            }

            if (map.get("suggestion").equals("review")){
                flag = false;
                //修改文章状态  3
                updateWmNews(wmNews,(short) 3,"当前文章中存在不确定内容");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }


        return flag;
    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    public boolean handleImageScan(List<String> images,WmNews wmNews) {

        boolean flag = true;

        //参数校验
        if (images == null || images.size() == 0){
            //TODO 这个忘了
            return flag;
        }
        //第一步：下载图片 minIO
        //图片去重,使用流
        List<String> image = images.stream().distinct().collect(Collectors.toList());
        //存放下载的图片
        ArrayList<byte[]> list = new ArrayList<>();


        try {
        for (String s : image) {
            byte[] bytes = fileStorageService.downLoadFile(s);

            //这里进行图片识别
            //TODO 从byte[]转换为butteredImage
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            String result = tess4jClient.doOCR(bufferedImage);
            
            //接着对图片识别出的文字进行过滤，使用前面的handleSensitiveScan
            boolean  isSensitive = handleSensitiveScan(result, wmNews);
            if (!isSensitive){
                return isSensitive;
            }

            list.add(bytes);
        }


        } catch (Exception e) {
            e.printStackTrace();
        }


        //第二步：审核图片
        try {
            Map map = greenImageScan.imageScan(list);
            if (map != null){
                //审核失败
                if (map.get("suggestion").equals("block")){
                    flag = false;
                    //更新文章状态 2
                    updateWmNews(wmNews,(short) 2,"当前图片中存在违规内容");
                }
                //不确定信息  需要人工审核
                if (map.get("suggestion").equals("review")){
                    flag = false;
                    //更新文章状态  3
                    updateWmNews(wmNews,(short)3,"当前图片中存在不确定内容");
                }
            }

        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 修改文章状态
     *           0 草稿
     *             1 提交（待审核）
     *             2 审核失败
     *             3 人工审核
     *             4 人工审核通过
     *             8 审核通过（待发布）
     *             9 已发布
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);

    }

    /**
     * 自管理敏感词过滤
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;
        //获取所有的敏感词
        //构建查询
        LambdaQueryWrapper<WmSensitive> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<WmSensitive> select = lambdaQueryWrapper.select(WmSensitive::getSensitives);
        //查询
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(select);

        List<String> list = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(list);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }


}
